package com.leenleda.ips;

import androidx.annotation.LayoutRes;
import androidx.annotation.NonNull;
import androidx.annotation.RequiresApi;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import androidx.databinding.DataBindingUtil;
import androidx.databinding.ViewDataBinding;

import android.Manifest;
import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.graphics.PixelFormat;
import android.hardware.display.DisplayManager;
import android.hardware.display.VirtualDisplay;
import android.media.Image;
import android.media.ImageReader;
import android.media.projection.MediaProjection;
import android.media.projection.MediaProjectionManager;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.provider.Settings;
import android.text.TextUtils;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.Display;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.google.gson.Gson;
import com.leenleda.ips.activity.CrashActivity;
import com.leenleda.ips.activity.ImageActivity;
import com.leenleda.ips.activity.InsertActivity;
import com.leenleda.ips.activity.WebActivity;
import com.leenleda.ips.entity.BaseEntity;
import com.leenleda.ips.entity.DataEntity;
import com.leenleda.ips.entity.MarqueeEntity;
import com.leenleda.ips.net.AEvent;
import com.leenleda.ips.net.AEventListener;
import com.leenleda.ips.net.NetInterface;
import com.leenleda.ips.receiver.Constant;
import com.leenleda.ips.receiver.KeepLiveService;
import com.leenleda.ips.receiver.ReceiverMsg;
import com.leenleda.ips.util.BaseUtils;
import com.leenleda.ips.util.FileData;
import com.leenleda.ips.util.FileUtils;
import com.leenleda.ips.util.GsonUtils;
import com.leenleda.ips.util.LogUtils;
import com.leenleda.ips.util.JavaScriptObject;
import com.leenleda.ips.util.NetUtils;
import com.leenleda.ips.util.TimeUtils;
import com.leenleda.ips.util.UShared;
import com.leenleda.ips.util.Utils;
import com.leenleda.ips.widget.DialogInput;
import com.leenleda.ips.widget.DialogPass;
import com.leenleda.ips.widget.DialogSetting;
import com.leenleda.ips.widget.MarqueeView;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.util.Map;

import static android.content.pm.PackageManager.PERMISSION_GRANTED;


public abstract class BaseActivity<T extends ViewDataBinding> extends AppCompatActivity implements AEventListener {

    private static BaseActivity mFor = null;
    public Handler mHandler = new Handler(Looper.getMainLooper());

    /**
     * 获取当前处于前台的activity
     */
    public static BaseActivity getForegroundActivity() {
        return mFor;
    }

    /**
     * 加载中显示头
     */
    public abstract void conTrollShow(int state, String ... data);

    public String tag = this.getClass().getSimpleName();


    public T bindingView;
    private RelativeLayout mContainer;
    public void setContentView(@LayoutRes int layoutResID){
        LogUtils.e(tag, "=======onCreate=====");
        initSys();
        bindingView = DataBindingUtil.inflate(getLayoutInflater(), layoutResID, null, false);
        RelativeLayout.LayoutParams params2 = new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
        bindingView.getRoot().setLayoutParams(params2);

//        checkStart("");
        mContainer = bindingView.getRoot().findViewById(R.id.container);
        getWindow().setContentView(bindingView.getRoot());
    }

    protected void initSys(){
        Window _window = getWindow();
        WindowManager.LayoutParams params = _window.getAttributes();
        params.systemUiVisibility = View.SYSTEM_UI_FLAG_HIDE_NAVIGATION|View.SYSTEM_UI_FLAG_IMMERSIVE;
//        params.systemUiVisibility = View.SYSTEM_UI_FLAG_HIDE_NAVIGATION;
        _window.setAttributes(params);
        _window.addFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);// 隐藏状态栏
        _window.addFlags(WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM);//禁用键盘

        requestPermission();
        Constant.NET_STATE = NetUtils.isNetworkAvailable(this);
        initServe();

    }

    private void startAim(Class<?> aim){
        Intent intent = new Intent(this, aim);
        Utils.startActivity(this, intent);
    }

    private void initServe(){
        LogUtils.e("SLKNDVLSDVSD", "===KeepLiveService===0===");
        Intent intent = new Intent(this, KeepLiveService.class);
        startService(intent);
    }

    public boolean checkPermission(){
        LogUtils.e(tag, "=======requestPermission===0====" + permissions);
        permissions = new String[]{ Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE};
        int permissionCheck = 0;
        for (String p : permissions) {
            permissionCheck += ContextCompat.checkSelfPermission(this, p);
        }
        if (permissionCheck != PackageManager.PERMISSION_GRANTED) {
            LogUtils.e(tag, "=======requestPermission===1====" + permissions);
            ActivityCompat.requestPermissions(this, permissions, 5);
            return false;
        }
        LogUtils.e(tag, "=======requestPermission====2===" + permissions);
        return true;
    }

    private String[] permissions;
    public void requestPermission() {
        if (!checkPermission())
            return;

        initBase();
        BaseEntity info = BaseUtils.getBase();
        if (info != null){
            switch (info.getHomeActivity()){
                case "com.leenleda.ips.activity.ImageActivity":
                    if (BaseActivity.this instanceof WebActivity){
                        startAim(ImageActivity.class);
                    }
                    break;
                case "com.leenleda.ips.activity.WebActivity":
                    if (BaseActivity.this instanceof ImageActivity){
                        startAim(WebActivity.class);
                    }
                    break;
            }
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        LogUtils.e(tag, "=======requestPermission====22211===" + requestCode);
        if (requestCode == 5){
            for (int result : grantResults){
                LogUtils.e(tag, "=======requestPermission====22222===" + result);
                if (result == PERMISSION_GRANTED){
                    requestPermission();
                    return;
                }
            }
            LogUtils.e(tag, "=======requestPermission====222333===" + requestCode);
        }
    }

    private static boolean checkAuthor = false;
    public void initBase(){
        LogUtils.e(tag, "-----checkAuthor--" + checkAuthor);
        if (checkAuthor)
            return;
//        BaseEntity entity = BaseUtils.getFileInfo();
        String ipS = "";
//        if (entity != null)
//            ipS = entity.getServiceIp();
//        LogUtils.e(tag, "-----ipS-0-" + ipS);
        if (ipS.isEmpty())
            ipS = FileUtils.getServiceIp();
        LogUtils.e(tag, "-----ipS-1-" + ipS);
        if(ipS.isEmpty())
            inputIpDialog("");
        else
            connectSer(ipS);
    }

    public boolean isNoAuthor() {
        return UShared.getBooleanValue(Constant.DEVICE_REGISTER);
    }

    public boolean isFirst() {
        return TextUtils.isEmpty(FileUtils.getServiceIp());
//        String serveIp = FileUtils.getServiceIp();
//        Log.e(tag, "=====inputIp==serveIp====" + serveIp);
//        return TextUtils.isEmpty(serveIp);
    }

    public void inputIpDialog(String str) {
        if (isDestroyed())
            return;
        handler.post(() -> ipDialog(Utils.getStringValue(str)));
    }

    private void ipDialog(String str) {
        boolean isStatic = UShared.getBooleanValue(Constant.LOAD_STATIC_URL);
        if (isStatic){
            AEvent.notifyListener(AEvent.TO_TOAST, true, "加载静态页面");
            return;
        }
        boolean haveRegister = isNoAuthor();
        if (haveRegister) {//当设备认证过了后不在提示认证失败提示弹框
            AEvent.notifyListener(AEvent.TO_TOAST, true, str);
//            Utils.showShortToast(str);
            return;
        }
        if (Utils.isFast())
            return;
        if (dialogInput != null){
            dialogInput.dismiss();
            dialogInput = null;
        }
        dialogInput = new DialogInput(this, new DialogInput.OnClickListener() {
            @Override
            public void onClick(String ipStr) {
                connectSer(ipStr);
            }
            @Override
            public void finish() {
                dialogInput.dismiss();
                dialogInput = null;
//                conTrollShow(Constant.INPUT_TIP, "点\"确认\"重新设置ip");
            }
        });
        dialogInput.show(FileUtils.getServiceIp(), str);
//        dialogInput.show();
        Constant.DIALOG_IS_SHOW = true;
    }

    public void misInput(){
        LogUtils.e(tag, "====misInput====" + dialogInput);
        if (dialogInput != null)
            dialogInput.dismiss();
        dialogInput = null;
        Constant.DIALOG_IS_SHOW = false;
    }

    public DialogInput dialogInput;
    public void buttonInput(View v) {
        if (dialogInput != null)
            dialogInput.buttonInput(v);
        if (pwd != null)
            pwd.buttonInput(v);
    }

    /**
     * 设备认证
     * @param ipStr
     */
    public void connectSer(String ipStr){
//        UShared.putString(Constant.SET_INPUT_IP, ipStr);
        LogUtils.e(tag, "--00---connectSer--" + ipStr);
        if (Utils.getStringValue(ipStr).isEmpty())
            return;
        BaseEntity entity = checkStart("");
        String time = TimeUtils.stampToDate(System.currentTimeMillis());//Constant.WEB_LOAD_TIME
        UShared.putString(Constant.WEB_LOAD_TIME, time);
        LogUtils.e("SLNVSDV", "======time======" + time);
        if (!Constant.NET_STATE) {
            inputIpDialog("网络连接异常");
            LogUtils.e(tag, "--connectSer---网络连接异常--" );
            return;
        }
        addListener();
        NetInterface.GetInstance().requestDate(ipStr, entity);
    }

    @Override
    protected void onResume() {
        super.onResume();
        mFor = this;
        addListener();
        scrollCheck();
    }

    public void scrollCheck(){
        String scrollStr = UShared.getString(Constant.SCROLL_BEAN);
        if (!Utils.getStringValue(scrollStr).isEmpty()) {
            MarqueeEntity entity = GsonUtils.getInstance().fromJson(scrollStr, MarqueeEntity.class);
            showRollMsg(entity);
        }
    }

    private void addListener(){
        AEvent.addListener(AEvent.NET_REQUEST, this);
        AEvent.addListener(AEvent.TO_TOAST, this);
        AEvent.addListener(AEvent.TO_DOWNLOAD, this);
        AEvent.addListener(AEvent.CHECK_UPDATE_TOOL, this);
    }

    @Override
    protected void onPause() {
        super.onPause();
        AEvent.removeListener(AEvent.NET_REQUEST, this);
        AEvent.removeListener(AEvent.TO_TOAST, this);
        AEvent.removeListener(AEvent.TO_DOWNLOAD, this);
        AEvent.removeListener(AEvent.CHECK_UPDATE_TOOL, this);
    }

    public Handler handler = new Handler(Looper.getMainLooper());
    @Override
    public void dispatchEvent(String eventId, boolean success, Object obj) {
        LogUtils.e(tag, "-----obj--" + obj);
        switch (eventId){
            case AEvent.CHECK_UPDATE_TOOL:
                LogUtils.e(tag, "-----CHECK_UPDATE_TOOL--" + success);
                if (!success) {
//                    Intent intent = new Intent(Constant.SERVICE);
//                    sendBroadcast(intent);
//
                    Intent jumpIntent = new Intent();
                    jumpIntent.setComponent(new ComponentName("com.leld.updatetool", Constant.SERVICE));
                    jumpIntent.setAction(Constant.SERVICE);
                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                        startForegroundService(jumpIntent);
                    } else {
                        startService(jumpIntent);
                    }
                }
                break;
            case AEvent.TO_DOWNLOAD:
                handler.post(()->{
                    LogUtils.e(tag,"------dispatchEvent-----" + obj);
                    if (success){
                        conTrollShow(Constant.REFRESH_DOWNLOAD, obj + "");
                    } else {
                        showToast(obj + "");
                        conTrollShow(Constant.REFRESH_DOWNLOAD, "-1");
                    }
                });
                break;
            case AEvent.TO_TOAST:
                showToast(obj + "");
                break;
            case AEvent.NET_REQUEST:
                LogUtils.e(tag, "-----NET_REQUEST--" + obj);
                if (!success){
                    inputIpDialog(Utils.getStringValue(obj + ""));
                    return;
                }
                if (obj == null)
                    return;
                Map source = null;
                try {
                    source = GsonUtils.getInstance().fromJson(obj + "", Map.class);
                } catch (Exception e){
                    showToast("服务器异常");
                    return;
                }
                int status = Double.valueOf(source.get("status") + "").intValue();
                if (status == 500){//授权到期
                    UShared.putBooleanValue(Constant.DEVICE_REGISTER, false);
                    LogUtils.e(tag, "-----404--" + source);
                    String msg = (String) source.get("msg");
                    showToast(msg);
                    return;
                } else if (status == 404){
                    showToast("连接服务器失败");
                    return;
                }
                UShared.putBooleanValue(Constant.DEVICE_REGISTER, true);
                if (status != 200)
                    return;
                String msg = source.get("msg") + "";
                LogUtils.e(tag, "-----msg--" + msg);
                handler.post(() -> {
                    if (msg.contains("认证成功")){
                        conTrollShow(Constant.DEVICE_PERMISSION_TRUE);
                        UShared.putString(Constant.DEVICE_PERMISSION_STATE, "");
                    } else {
                        String str = "还有" + msg + "天，认证到期";
                        conTrollShow(Constant.DEVICE_PERMISSION_FALSE, str);
                        UShared.putString(Constant.DEVICE_PERMISSION_STATE, str);
                    }
                });

                LogUtils.e(tag, "-----source--" + source);
                Map data = GsonUtils.getInstance().fromJson(new Gson().toJson(source.get("data")), Map.class);
                if (data == null){
                    showToast("连接服务器失败");
                    return;
                }
                String msgData = Utils.getStringValue(data.get("sendNoticeMessageVo") + "");
                LogUtils.e("SLDNVSDV", "======msgData====" + msgData);
                MarqueeEntity bean = GsonUtils.getInstance().fromJson(msgData, MarqueeEntity.class);
                LogUtils.e("SLDNVSDV", "======bean====" + bean);
                if(bean != null && bean.getRollTime() > 1){
                    String model = Build.MODEL;
                    LogUtils.e(tag, "=======model======" + model);
                    if (model.equals("A40I")){
                        NetInterface.pushMsg(bean);
                        return;
                    } else {
                        showRollMsg(bean);
                    }
                } else {
                    missRollMsg(true);
                }
                DataEntity dataE = FileData.getDeviceInfo(0);
                dataE.setMediaType((String) data.get("infoType"));
                dataE.setMediaUrl(Utils.getStringValue((String) data.get("infoUrl")));
                if (data.get("speed") != null){
                    Constant.voiceSpeed = ("" + data.get("speed")).replace(".0", "");
                    dataE.setVoiceSpeed(Constant.voiceSpeed);//Double.valueOf(data.get("cacheSize") + "").intValue();
                }
                if (data.get("cacheSize") != null){
                    Constant.cacheSize = Double.valueOf(data.get("cacheSize") + "").intValue();
                    UShared.putInt("cacheSize", Constant.cacheSize);
                    dataE.setCacheSize(Constant.cacheSize);
                }
                if (data.get("volumeValue") != null){
                    int voice = Double.valueOf(data.get("volumeValue") + "").intValue();
                    JavaScriptObject.sendDeviceControl(Constant.DEVICE_VOICE_SET, voice);
                    dataE.setVolume(voice);
                }

//                LogUtils.e(tag, "=====ipStr_new==2====" + UShared.getString(Constant.SET_INPUT_IP));
                FileData.setDeviceInfo(dataE);
                LogUtils.e(tag, "=====dataE==2====" + dataE);

                UShared.putString(Constant.PUBLISH_URL, dataE.getMediaUrl());
                UShared.putString(Constant.PUBLISH_TYPE, dataE.getMediaType());

                checkAuthor = true;
//                FileUtils.setServeIp(UShared.getString(Constant.SET_INPUT_IP));
                FileUtils.setServeIp(UShared.getString(Constant.SET_INPUT_IP));//保存serviceIP
                checkStart( dataE.getMediaType());
                misInput();
                handler.post(() -> conTrollShow(Constant.SET_MEDIA_DATA,dataE.getMediaType()));
                break;
        }
    }

//    ***********************************

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        LogUtils.e("BaseClick", "==keyCode===" + keyCode);
//        if (keyCode == KeyEvent.KEYCODE_BACK) {
//            return true;
//        } else if (keyCode == KeyEvent.KEYCODE_BACK){
//
//        }
        switch (keyCode){
            case KeyEvent.KEYCODE_BACK:
                LogUtils.e("LSNVSDLV", "=====takeScreenShot===111=====");
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                    LogUtils.e("LSNVSDLV", "=====takeScreenShot===222=====");
                }
                btnBack(null);
                return true;
            case KeyEvent.KEYCODE_ENTER:
            case KeyEvent.KEYCODE_DPAD_CENTER:
                inputIpDialog("");
                return true;
        }

        return super.onKeyDown(keyCode, event);
    }

    /**
     * 右上角返回键
     */
    public void btnBack(View view){
        String crashStr = UShared.getString(Constant.CRASH_TAG);
        LogUtils.e("crashStr", "===Devices=finish=========" + crashStr);
        if (!Utils.dKey("btnBack"))
            return;

        String pwd = Utils.getStringValue(UShared.getString("set_pwd"));
        if (pwd.isEmpty())
            showSet();
        else
            showPwd();
        return;
    }

    private DialogPass pwd = null;
    private void showPwd(){
        missPwd();
        if (pwd == null){
            pwd = new DialogPass(this, new DialogPass.OnClickListener() {
                @Override
                public void onClick() {
                    back();
                    showSet();
                }

                @Override
                public void back() {
                    missPwd();
                }
            });
        }
        pwd.show();
    }

    private void missPwd(){
        if (pwd != null)
            pwd.dismiss();
        pwd = null;
    }

    private DialogSetting setDialog;
    private void showSet(){
        setDialog = null;
        setDialog = new DialogSetting(this, state -> {
            setDialog.dismiss();
            setDialog = null;
            Intent intent = null;
            Log.e("SLKVNSDV", "=====state======" + state);
            switch (state){
                case 1:
                    BaseUtils.clearService();
                    showToast("请重新打开app");
//                    Utils.showShortToast("请重新打开app");
                    intent = new Intent(this, WebActivity.class);
                    PendingIntent restartIntent = PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
                    AlarmManager mgr = (AlarmManager)getSystemService(Context.ALARM_SERVICE);
                    mgr.set(AlarmManager.RTC, System.currentTimeMillis() + 2000, restartIntent);
                    android.os.Process.killProcess(android.os.Process.myPid());
                    break;
                case 2:
                    Constant.APP_TEST = !Constant.APP_TEST;
                    String type = getType();
                    conTrollShow(Constant.SET_MEDIA_DATA,Constant.PUBLISH_WEB);
                    break;
                case 3:
                    intent = new Intent(BaseActivity.this, CrashActivity.class);
                    Utils.startActivity(BaseActivity.this, intent);
                    break;
                case 4:
                    Constant.toAim = -2;//提醒更新工具，不用主动打开自己
                    ReceiverMsg.sendBroad(this);
//                    finish();
//                    System.exit(0);
                    Constant.APP_RESTART = false;
                    intent = new Intent();
                    intent.setAction(Intent.ACTION_MAIN);// 设置Intent动作
                    intent.addCategory(Intent.CATEGORY_HOME);// 设置Intent种类
                    startActivity(intent);
                    finish();
                    break;
            }
        });
        setDialog.show();
    }

//    ***********************************

    //========插播==========
//    private PopLayout textWindow;
    public void showRollMsg(MarqueeEntity entity){
        if (Utils.dKey("showRollMsg"))
            return;
        if (parentView != null)
            missRollMsg(true);
        handler.post(() -> {
            if (mContainer == null)
                return;
            View childView = null;
            int height = mContainer.getHeight() * 1 / 4;
            if (entity.isFixed()){
                childView = View.inflate(this, R.layout.pop_text, null);//这里是你弹窗的UI

                ((TextView) childView).setTextColor(Color.parseColor(entity.getTextColor()));
                ((TextView) childView).setTextSize(entity.getTextSize());
                ((TextView) childView).setText(entity.getText());

                WindowManager.LayoutParams params = new WindowManager.LayoutParams();
                params.height = height;
                params.width = LinearLayout.LayoutParams.WRAP_CONTENT;
                childView.setLayoutParams(params);
            } else {
                childView = View.inflate(this, R.layout.pop_marquee, null);//这里是你弹窗的UI

                ((MarqueeView) childView).setTextColor(Color.parseColor(entity.getTextColor()));
                ((MarqueeView) childView).setTextSize(100);
                ((MarqueeView) childView).setViewFrom(entity.isRollType() ? 1 : 0);
                ((MarqueeView) childView).setTextSpeed(entity.getRollSpeed());
                ((MarqueeView) childView).setText(entity.getText());
                ((MarqueeView) childView).startScroll();

                WindowManager.LayoutParams params = new WindowManager.LayoutParams();
                params.height = height;

                Display display = BaseActivity.getForegroundActivity().getWindowManager().getDefaultDisplay();
//        int width = display.getWidth() * 2 / 3;
                int width = display.getWidth();
                params.width = width;
                childView.setLayoutParams(params);
            }
            parentView = new LinearLayout(this);
            final LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(
                    LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.MATCH_PARENT);
            parentView.setLayoutParams(layoutParams);
//            parentView.setOnTouchListener(this);
            parentView.setGravity(Gravity.CENTER_HORIZONTAL);
//            parentView.setBackgroundColor(getResources().getColor(R.color.transparent2));
            int pos = Gravity.BOTTOM;
            switch (entity.getGravity()){
                case 1:
                    pos = Gravity.TOP;
                    break;
                case 2:
                    pos = Gravity.CENTER_VERTICAL;
                    break;
                default:
                case 3:
                    pos = Gravity.BOTTOM;
                    break;
            }
            LogUtils.e("SFKSDLFDF", "===close==0000000==" + entity.getGravity() + ",pos=" + pos);
            parentView.setVerticalGravity(pos);
            parentView.addView(childView);
            mContainer.addView(parentView);
            entity.setCloseTime(Utils.getSetTime() / 1000 + entity.getRollTime());
            duringTime = Utils.getSetTime() / 1000 + entity.getRollTime();
            String scrollStr = GsonUtils.getInstance().toJson(entity);
            UShared.putString(Constant.SCROLL_BEAN, scrollStr);
        });
    }

    public void missRollMsg(boolean close){
        LogUtils.i("SFKSDLFDF", "===close==1==" + close + ",parentView=" + parentView + ",mContaier=" + mContainer);
        if (parentView == null || mContainer == null)
            return;
        if (!close){
            long cur = Utils.getSetTime() / 1000;
            if (cur < duringTime)
                return;
        }
        miss();
        LogUtils.e("SFKSDLFDF", "===close==2==" + close + ",parentView=" + parentView + ",mContaier=" + mContainer);
    }

    private void miss(){
        handler.post(() -> {
            UShared.putString(Constant.SCROLL_BEAN, "");
            mContainer.removeView(parentView);
            parentView = null;
        });
    }

    private static long duringTime = 0;
    private static LinearLayout parentView = null;

    public void insertRes(String strData){
        if (Utils.getStringValue(strData).isEmpty())
            return;
        Intent intent = new Intent(this, InsertActivity.class);
        intent.putExtra("strData", strData);
        Utils.startActivity(this, intent);
    }

    public BaseEntity checkStart(String aim) {
        PackageManager packageManager = getPackageManager();
        PackageInfo packageInfo = null;
        BaseEntity info = new BaseEntity();
        LogUtils.e(tag, "===info1==" + info);
        try {
            packageInfo = packageManager.getPackageInfo(getPackageName(), 0);
            String aimAct = "";
            switch (aim){
                case Constant.PUBLISH_SOURCE:
                    aimAct = "com.leenleda.ips.activity.ImageActivity";
                    info.setHomeActivity(aimAct);
                    break;
                default:
                case Constant.PUBLISH_WEB:
                    aimAct = "com.leenleda.ips.activity.WebActivity";
                    info.setHomeActivity(aimAct);
                    break;
                case Constant.PUBLISH_LIVE:
                    aimAct = "com.leenleda.ips.activity.LiveActivity";
                    info.setHomeActivity(aimAct);
                    break;
//                default:
//                    break;
            }
            info.setPackageName(packageInfo.packageName);
            info.setVersionCode(packageInfo.versionCode);
//            info.setDeviceMac(FileUtils.getDeviceMac());
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
        info.setServiceIp(FileUtils.getServiceIp());
        LogUtils.e(tag, "===info2==" + FileUtils.getServiceIp());
        boolean te = BaseUtils.setDeviceInfo(info);
        LogUtils.e(tag, "--Base---==deviceInfo=-te-" + te);
        ReceiverMsg.sendBroad(this);
        return info;
    }

    public String getType(){
        boolean cc = checkPermission();
        LogUtils.e(tag, "=====getType====checkPermission==" + cc );
        if (!cc)
            return "";
        DataEntity info = FileData.getDeviceInfo(1);
//        LogUtils.e(tag, "=====getType======" + info );
        String type = "";
        if (info != null)
            type = info.getMediaType();
        if (type.isEmpty())
            type = UShared.getString(Constant.PUBLISH_TYPE);
        LogUtils.e(tag, "=====type======" + type );
        return type;
    }

    public String getData(){
        DataEntity info = FileData.getDeviceInfo(2);
        LogUtils.e(tag, "=====getData======" + info );
        String data = "";
        if (info != null)
            data = info.getMediaUrl();
        if (data.isEmpty())
            data = UShared.getString(Constant.PUBLISH_URL);
//        LogUtils.e(tag, "=====data======" + data );
        return data;
    }

    public void showToast(String str){
        handler.post(() -> Utils.showShortToast(str));
    }

    //*************************截图**************************
    public static final int EVENT_SCREENSHOT = 22;//截图事件
    private MediaProjectionManager mediaProjectionManager;
    private MediaProjection mediaProjection;
    private Image image;
    private static String fileName = "";
    @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
    public void takeScreenShot(String fileName) {
        this.fileName = fileName;
        mediaProjectionManager = (MediaProjectionManager)
                getApplication().getSystemService(Context.MEDIA_PROJECTION_SERVICE);
        startActivityForResult(mediaProjectionManager.createScreenCaptureIntent(), EVENT_SCREENSHOT);
    }

    @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        Log.e("takeScreenShot", "onActivityResult...requestCode=" + requestCode + ",resultCode=" + resultCode);
        if (requestCode == EVENT_SCREENSHOT) {
            super.onActivityResult(requestCode, resultCode, data);
            Log.e("takeScreenShot", "captureScreen...");
            DisplayMetrics displayMetrics = new DisplayMetrics();
            WindowManager windowManager = (WindowManager) this.getSystemService(WINDOW_SERVICE);
            windowManager.getDefaultDisplay().getMetrics(displayMetrics);
            int width = displayMetrics.widthPixels;
            int height = displayMetrics.heightPixels;
            Log.e("takeScreenShot", "displayMetrics width=" + width + ", height=" + height);
            ImageReader mImageReader = ImageReader.newInstance(width, height, PixelFormat.RGBA_8888, 2);
            mediaProjection = mediaProjectionManager.getMediaProjection(resultCode, data);
            VirtualDisplay virtualDisplay = mediaProjection.createVirtualDisplay("screen-mirror", width, height,
                    displayMetrics.densityDpi, DisplayManager.VIRTUAL_DISPLAY_FLAG_AUTO_MIRROR, mImageReader.getSurface(), null, null);
            new Handler().postDelayed(new Runnable() {
                @Override
                public void run() {
                    try {
                        image = mImageReader.acquireLatestImage();
                        if (image != null) {
                            final Image.Plane[] planes = image.getPlanes();
                            final ByteBuffer buffer = planes[0].getBuffer();
                            int width = image.getWidth();
                            int height = image.getHeight();
                            Log.e("whh0914", "image width=" + width + ", height=" + height);
                            int pixelStride = planes[0].getPixelStride();
                            int rowStride = planes[0].getRowStride();
                            int rowPadding = rowStride - pixelStride * width;
                            Bitmap bitmap = Bitmap.createBitmap(width + rowPadding / pixelStride, height, Bitmap.Config.ARGB_8888);
                            bitmap.copyPixelsFromBuffer(buffer);
                            bitmap = Bitmap.createScaledBitmap(bitmap, bitmap.getWidth(), bitmap.getHeight(), false);
                            if (bitmap != null) {
                                Log.e("whh0914", "屏幕截图成功!");
                                saveBitmap(bitmap);
                            }
                            bitmap.recycle();
                        }
                    } catch (Exception e) {
                        Log.e("takeScreenShot", "截图出现异常：" + e.toString());
                    } finally {
                        if (image != null) {
                            image.close();
                        }
                        if (mImageReader != null) {
                            mImageReader.close();
                        }
                        if (virtualDisplay != null) {
                            virtualDisplay.release();
                        }
                        //必须代码，否则出现BufferQueueProducer: [ImageReader] dequeueBuffer: BufferQueue has been abandoned
                        mImageReader.setOnImageAvailableListener(null, null);
                        mediaProjection.stop();
                    }
                }
            }, 100);
        }
    }
    //保存bitmap文件
    public static void saveBitmap(Bitmap bitmap) {
//        String fileName = System.currentTimeMillis() + ".png";
        File file = new File(FileUtils.getPath() , fileName);
//        File f = new File(filePath);
        FileOutputStream out = null;
        try {
            out = new FileOutputStream(file);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        bitmap.compress(Bitmap.CompressFormat.PNG, 100, out);
        try {
            out.flush();
            out.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        LogUtils.e("takeScreenShot", "==bundle===takeScreenShot===1===" + fileName);
    }

    private void checkFlo(){
        LogUtils.e(tag, "===canDrawOverlays===1===" );
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            try {
                if (!Settings.canDrawOverlays(this)) {//若未授权则请求权限
                    Intent intent = new Intent(Settings.ACTION_MANAGE_OVERLAY_PERMISSION);
                    intent.setData(Uri.parse("package:" + getPackageName()));
                    startActivityForResult(intent, 0);
                }
            } catch (Exception e){
                LogUtils.e(tag, "===canDrawOverlays===e===" + e);
            }
        }
    }
}
